package com.gable.exhibition.service.impl;

import com.gable.common.util.MoneyFormatUtil;
import com.gable.common.util.ReturnResultUtil;
import com.gable.common.util.StringUtil;
import com.gable.common.util.UUIDGenerator;
import com.gable.exhibition.dao.DeviceDao;
import com.gable.exhibition.dao.EventDao;
import com.gable.exhibition.dao.FileDao;
import com.gable.exhibition.dao.RepairDao;
import com.gable.exhibition.model.Device;
import com.gable.exhibition.model.File;
import com.gable.exhibition.model.Repair;
import com.gable.exhibition.model.User;
import com.gable.exhibition.service.DeviceService;
import com.gable.exhibition.util.InsideOutsideUtil;
import com.gable.exhibition.util.MessageUtil;
import com.gable.exhibition.view.DeviceView;
import com.gable.exhibition.view.ImportExcelDeviceModel;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.sql.*;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.Date;

/**
 * Created by Lesson on 2018/2/23.
 */
@Service("deviceService")
public class DeviceServiceImpl implements DeviceService {

    @Autowired
    DeviceDao deviceDao;

    @Autowired
    RepairDao repairDao;

    @Override
    public ReturnResultUtil queryDeviceList(DeviceView deviceView) {
        int count = deviceDao.queryDeviceCount(deviceView);
        List<DeviceView> list = deviceDao.queryDeviceList(deviceView);
        for(DeviceView dv : list){
            if(dv.getContractView() == null || dv.getInstallDate() == null || dv.getContractView().getDeviceWarrantyPeriod() == null){
                continue;
            }
            String guaranteeLastDate = InsideOutsideUtil.queryDeviceGuaranteedDate(dv.getInstallDate(), dv.getContractView().getDeviceWarrantyPeriod());
            String medicalSecurity = InsideOutsideUtil.queryMedicalSecurity(guaranteeLastDate);
            dv.getContractView().setMedicalSecurity(medicalSecurity);
        }
        DeviceView deviceView1 = new DeviceView();
        deviceView1.setCount(count);
        deviceView1.setList(list);
        return new ReturnResultUtil(200, MessageUtil.QUERYSUCCESS,deviceView1);
    }

    @Override
    @Transactional(rollbackFor = RuntimeException.class)
    public ReturnResultUtil addOrUpdateDevice(DeviceView deviceView) {
        if(deviceView.getSn()!=null){
            Map map = new HashMap();
            map.put("deviceId",deviceView.getDeviceId());
            map.put("sn",deviceView.getSn());
            int count = deviceDao.checkDeviceSn(map);
            if(count > 0){
                return new ReturnResultUtil(500,MessageUtil.SNEXITIS);
            }
        }

        if(deviceView.getDeviceModel()!=null){
            deviceView.setDeviceModel(deviceView.getDeviceModel().toUpperCase());
        }
        int result = 0;
        if(deviceView.getDeviceId()==null){
            deviceView.setDeviceId(UUIDGenerator.getUniqueLong());
            result = deviceDao.insertSelective(deviceView);

            //无设备保修
            if(deviceView.getRepairId()!=null){
                Repair repair = repairDao.selectByPrimaryKey(deviceView.getRepairId());
                repair.setDeviceId(deviceView.getDeviceId());
                repair.setHospitalId(deviceView.getHospitalId());
                repairDao.updateByPrimaryKeySelective(repair);
            }
        }else{
            result = deviceDao.updateByPrimaryKeySelective(deviceView);
        }
        if(result > 0){
            return new ReturnResultUtil(200,MessageUtil.SAVESUCCESS);
        }else{
            return new ReturnResultUtil(500,MessageUtil.SAVEFAIL);
        }
    }

    @Override
    public ReturnResultUtil queryDeviceInfo(Long deviceId) {
        DeviceView deviceView = deviceDao.queryDeviceInfo(deviceId);
        if(deviceView.getContractView() != null){
            String enableTime = deviceView.getEnableTime(); //获取设备启用时间
            Integer deviceWarrantyPeriod =  deviceView.getContractView().getDeviceWarrantyPeriod();//获取设备的厂家保修期
            Integer supplierWarrantyPeriod = deviceView.getContractView().getSupplierWarrantyPeriod(); //获取设备的经销商保修期
            String manufacturerLastDate = InsideOutsideUtil.queryDeviceGuaranteedDate(enableTime, deviceWarrantyPeriod); //获取厂家维保的最后日期
            deviceView.getContractView().setManufacturerLastDate(manufacturerLastDate);
            String supplierLastDate = InsideOutsideUtil.queryDeviceGuaranteedDate(enableTime, supplierWarrantyPeriod); //获取经销商维保的最后日期
            deviceView.getContractView().setSupplierLastDate(supplierLastDate);

            String medicalSecurity = null;
            Long value = InsideOutsideUtil.queryWarranty(enableTime,deviceWarrantyPeriod,supplierWarrantyPeriod);
            if(value.longValue() == 1103){
                medicalSecurity="保外";
            }else if(value.longValue() == 1102){
                medicalSecurity="厂家维保";
            }else if(value.longValue() == 1105){
                medicalSecurity="经销商维保";
            }
            deviceView.getContractView().setMedicalSecurity(medicalSecurity);
        }
        if(deviceView.getUpkeepCycle() != null && deviceView.getLastUpkeepDate()!=null){
            String nextUpkeepDate = queryNextUpkeepDate(deviceView.getLastUpkeepDate(),deviceView.getUpkeepCycle());
            deviceView.setNextUpkeepDate(nextUpkeepDate);
        }
        deviceView.setPriceStr(MoneyFormatUtil.MoneyToString(deviceView.getPrice()));
        return new ReturnResultUtil(200,MessageUtil.QUERYSUCCESS,deviceView);
    }

    //根据上次保养时间和保养周期推出下次保养时间
    private String queryNextUpkeepDate(String lastUpkeepDate,Integer upkeepCycle){
        try {
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
            Calendar calendar = Calendar.getInstance();
            Date date = sdf.parse(lastUpkeepDate);
            calendar.setTime(date);
            calendar.add(Calendar.MONTH,upkeepCycle);
            return sdf.format(calendar.getTime());
        }catch (Exception e){
            e.printStackTrace();
        }
        return null;
    }


    @Override
    @Transactional(rollbackFor = RuntimeException.class)
    public ReturnResultUtil saveDeviceByExcel(List<ImportExcelDeviceModel> list, User user) {
        DateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        int count = 0;
        for(ImportExcelDeviceModel id : list){
            Device device = new Device();
            device.setDeviceId(UUIDGenerator.getUniqueLong());
            device.setDeviceName(id.getDeviceName());
            device.setDeviceModel(id.getDeviceModel());
            device.setSn(id.getSn());
            device.setHospitalId(id.getHospitalId());
            device.setManufacturerId(id.getManufacturerId());
            device.setMaintainerId(id.getMaintainerId());
            device.setDepartment(id.getDepartment());
            device.setAssetsNo(id.getAssetsNo());
            device.setPlaceOrigin(id.getPlaceOrigin());
            device.setSpecifications(id.getSpecifications());
            device.setPrice(id.getPrice());
            device.setQuantity(id.getQuantity());
            device.setAttachment(id.getAttachment());
            device.setUpkeepCycle(id.getUpkeepCycle());
            device.setLastUpkeepDate(id.getLastUpkeepDate());
            device.setInstallDate(id.getInstallDate());
            device.setAcceptanceDate(id.getAcceptanceDate());
            device.setPurchaseDate(id.getPurchaseDate());
            device.setManufactureDate(id.getManufactureDate());
            device.setResponsiblePerson(id.getResponsiblePerson());
            device.setDeviceStatus(id.getDeviceStatus());
            device.setDeviceTypeId(id.getDeviceTypeId());
            device.setDeviceTypeSubId(id.getDeviceTypeSubId());
            device.setRemark(id.getRemark());
            device.setIsDel(0);
            device.setCreateTime(df.format(new Date()));
            device.setCreatePerson(user.getUserId());
            int result = deviceDao.insertSelective(device);
            if(result > 0){
                count++;
            }
        }

        if(count != list.size()){
            Device d = null;
            d.getDeviceId();
        }
        return new ReturnResultUtil(200,MessageUtil.SAVESUCCESS);
    }

    @Override
    public ReturnResultUtil queryDeviceByKeyword(Map map) {
        List<DeviceView> list = deviceDao.queryDeviceByKeyword(map);
        List<DeviceView> lists = deviceDao.queryDeviceByRepairAndKeyword(map);
        List<DeviceView> listss = deviceDao.queryDeviceByContractAndKeyword(map);
        Map<String, List<DeviceView>> maps = new HashMap<String, List<DeviceView>>();
        maps.put("device",list);
        maps.put("repair",lists);
        maps.put("contract",listss);
        return new ReturnResultUtil(200,MessageUtil.QUERYSUCCESS,maps);
    }
}
